package repository

import (
	"aigen-todo/internal/interfaces"
	"aigen-todo/internal/models"

	"gorm.io/gorm"
)

type TaskRepository struct {
	db *gorm.DB
}

// 确保 TaskRepository 实现了 interfaces.TaskRepositoryInterface 接口
var _ interfaces.TaskRepositoryInterface = &TaskRepository{}

func NewTaskRepository(db *gorm.DB) *TaskRepository {
	return &TaskRepository{db: db}
}

func (r *TaskRepository) Create(task *models.Task) error {
	return r.db.Create(task).Error
}

func (r *TaskRepository) GetByID(id uint64) (*models.Task, error) {
	var task models.Task
	err := r.db.Where("id = ?", id).First(&task).Error
	if err != nil {
		return nil, err
	}
	return &task, nil
}

func (r *TaskRepository) GetByUserID(userID uint64) ([]models.Task, error) {
	var tasks []models.Task
	err := r.db.Where("user_id = ?", userID).Find(&tasks).Error
	return tasks, err
}

func (r *TaskRepository) GetByGroupID(groupID uint64) ([]models.Task, error) {
	var tasks []models.Task
	err := r.db.Where("group_id = ?", groupID).Find(&tasks).Error
	return tasks, err
}

func (r *TaskRepository) GetMyDayTasks(userID uint64) ([]models.Task, error) {
	var tasks []models.Task
	err := r.db.Where("user_id = ? AND is_my_day = ?", userID, true).Find(&tasks).Error
	return tasks, err
}

func (r *TaskRepository) Update(task *models.Task) error {
	return r.db.Save(task).Error
}

func (r *TaskRepository) Delete(id uint64) error {
	return r.db.Delete(&models.Task{}, id).Error
}

func (r *TaskRepository) ChangeGroup(taskID, groupID uint64) error {
	return r.db.Model(&models.Task{}).Where("id = ?", taskID).Update("group_id", groupID).Error
}
